using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.IO;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 自主规划服务 - Agent根据用户需求自主规划人物及工作流并实施
    /// </summary>
    public class AutonomousPlanningService
    {
        private readonly ILogger<AutonomousPlanningService> _logger;
        private readonly IAIService _aiService;
        private readonly EnhancedIntentRecognizer _intentRecognizer;
        private readonly CharacterPlanningEngine _characterPlanner;
        private readonly WorkflowOrchestrationEngine _workflowEngine;
        private readonly ExecutionMonitoringService _executionMonitor;
        private readonly IProjectService _projectService;
        private readonly IDataStorageService _dataStorage;

        public AutonomousPlanningService(
            ILogger<AutonomousPlanningService> logger,
            IAIService aiService,
            EnhancedIntentRecognizer intentRecognizer,
            CharacterPlanningEngine characterPlanner,
            WorkflowOrchestrationEngine workflowEngine,
            ExecutionMonitoringService executionMonitor,
            IProjectService projectService,
            IDataStorageService dataStorage)
        {
            _logger = logger;
            _aiService = aiService;
            _intentRecognizer = intentRecognizer;
            _characterPlanner = characterPlanner;
            _workflowEngine = workflowEngine;
            _executionMonitor = executionMonitor;
            _projectService = projectService;
            _dataStorage = dataStorage;
        }

        /// <summary>
        /// 根据用户需求自主规划并实施
        /// </summary>
        public async Task<AutonomousPlanResult> PlanAndExecuteAsync(string userRequest, string? projectId = null, IProgress<(int progress, string message)>? progressCallback = null)
        {
            try
            {
                _logger.LogInformation($"开始自主规划处理用户请求: {userRequest}");

                // 1. 意图理解和需求分析
                progressCallback?.Report((10, "正在分析用户需求..."));
                var intent = await AnalyzeUserIntentAsync(userRequest, projectId);

                // 2. 生成综合规划方案
                progressCallback?.Report((30, "正在生成规划方案..."));
                var planningResult = await GenerateComprehensivePlanAsync(intent);

                // 3. 执行规划方案
                progressCallback?.Report((60, "正在执行规划方案..."));
                var executionResult = await ExecutePlanAsync(planningResult);

                // 4. 监控和优化
                progressCallback?.Report((90, "正在优化和生成报告..."));
                var finalResult = await MonitorAndOptimizeAsync(executionResult);

                // 5. 保存规划文件
                progressCallback?.Report((95, "正在保存规划文件..."));
                await SavePlanningFilesAsync(finalResult, projectId);

                progressCallback?.Report((100, "规划完成"));
                _logger.LogInformation("自主规划处理完成");
                return finalResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "自主规划处理失败");
                throw;
            }
        }

        /// <summary>
        /// 分析用户意图
        /// </summary>
        private async Task<EnhancedUserIntent> AnalyzeUserIntentAsync(string userRequest, string? projectId)
        {
            // 获取项目上下文
            var projectContext = await GetProjectContextAsync(projectId);
            
            // 使用增强的意图识别器
            var complexIntent = await _intentRecognizer.AnalyzeUserIntentAsync(userRequest);
            
            // 构建增强的用户意图
            var enhancedIntent = new EnhancedUserIntent
            {
                OriginalRequest = userRequest,
                ComplexIntent = complexIntent,
                ProjectContext = projectContext,
                RequiresCharacterPlanning = DetermineCharacterPlanningNeed(complexIntent),
                RequiresWorkflowPlanning = DetermineWorkflowPlanningNeed(complexIntent),
                PlanningScope = DeterminePlanningScope(complexIntent),
                AnalyzedAt = DateTime.Now
            };

            return enhancedIntent;
        }

        /// <summary>
        /// 生成综合规划方案
        /// </summary>
        private async Task<ComprehensivePlan> GenerateComprehensivePlanAsync(EnhancedUserIntent intent)
        {
            var plan = new ComprehensivePlan
            {
                UserIntent = intent,
                CreatedAt = DateTime.Now
            };

            // 并行生成不同类型的规划
            var tasks = new List<Task>();

            if (intent.RequiresCharacterPlanning)
            {
                tasks.Add(Task.Run(async () => 
                {
                    plan.CharacterPlan = await _characterPlanner.GenerateCharacterPlanAsync(intent);
                }));
            }

            if (intent.RequiresWorkflowPlanning)
            {
                tasks.Add(Task.Run(async () => 
                {
                    plan.WorkflowPlan = await _workflowEngine.GenerateWorkflowPlanAsync(intent);
                }));
            }

            // 等待所有规划任务完成
            await Task.WhenAll(tasks);

            // 整合和优化规划
            plan = await IntegrateAndOptimizePlanAsync(plan);

            return plan;
        }

        /// <summary>
        /// 执行规划方案
        /// </summary>
        private async Task<PlanExecutionResult> ExecutePlanAsync(ComprehensivePlan plan)
        {
            var executionResult = new PlanExecutionResult
            {
                Plan = plan,
                StartedAt = DateTime.Now,
                Status = ExecutionStatus.Running
            };

            try
            {
                // 创建执行上下文
                var executionContext = new Models.ExecutionContext
                {
                    Plan = plan,
                    ProjectId = plan.UserIntent.ProjectContext?.ProjectId,
                    ExecutionId = Guid.NewGuid().ToString()
                };

                // 按优先级和依赖关系执行任务
                if (plan.CharacterPlan != null)
                {
                    var characterResult = await ExecuteCharacterPlanAsync(plan.CharacterPlan, executionContext);
                    executionResult.CharacterExecutionResult = characterResult;
                }

                if (plan.WorkflowPlan != null)
                {
                    var workflowResult = await ExecuteWorkflowPlanAsync(plan.WorkflowPlan, executionContext);
                    executionResult.WorkflowExecutionResult = workflowResult;
                }

                executionResult.Status = ExecutionStatus.Completed;
                executionResult.CompletedAt = DateTime.Now;
            }
            catch (Exception ex)
            {
                executionResult.Status = ExecutionStatus.Failed;
                executionResult.ErrorMessage = ex.Message;
                executionResult.CompletedAt = DateTime.Now;
                _logger.LogError(ex, "规划执行失败");
            }

            return executionResult;
        }

        /// <summary>
        /// 监控和优化执行结果
        /// </summary>
        private async Task<AutonomousPlanResult> MonitorAndOptimizeAsync(PlanExecutionResult executionResult)
        {
            // 使用执行监控服务分析结果
            var monitoringResult = await _executionMonitor.AnalyzeExecutionResultAsync(executionResult);
            
            // 生成优化建议
            var optimizationSuggestions = await GenerateOptimizationSuggestionsAsync(executionResult, monitoringResult);
            
            // 构建最终结果
            var finalResult = new AutonomousPlanResult
            {
                ExecutionResult = executionResult,
                MonitoringResult = monitoringResult,
                OptimizationSuggestions = optimizationSuggestions,
                Success = executionResult.Status == ExecutionStatus.Completed,
                CompletedAt = DateTime.Now
            };

            // 如果有优化建议且用户允许，自动应用优化
            if (optimizationSuggestions.Any() && ShouldAutoApplyOptimizations(optimizationSuggestions))
            {
                finalResult = await ApplyOptimizationsAsync(finalResult);
            }

            return finalResult;
        }

        /// <summary>
        /// 执行角色规划
        /// </summary>
        private async Task<CharacterExecutionResult> ExecuteCharacterPlanAsync(CharacterPlan characterPlan, Models.ExecutionContext context)
        {
            return await _characterPlanner.ExecutePlanAsync(characterPlan, context);
        }

        /// <summary>
        /// 执行工作流规划
        /// </summary>
        private async Task<WorkflowExecutionResult> ExecuteWorkflowPlanAsync(WorkflowPlan workflowPlan, Models.ExecutionContext context)
        {
            return await _workflowEngine.ExecutePlanAsync(workflowPlan, context);
        }

        /// <summary>
        /// 获取项目上下文
        /// </summary>
        private async Task<ProjectContext?> GetProjectContextAsync(string? projectId)
        {
            if (string.IsNullOrEmpty(projectId))
                return null;

            try
            {
                var project = await _projectService.GetProjectAsync(int.Parse(projectId));
                if (project == null)
                    return null;

                return new ProjectContext
                {
                    ProjectId = projectId,
                    ProjectName = project.Name,
                    ProjectType = project.Type,
                    ProjectPath = project.RootPath,
                    // 可以添加更多上下文信息
                };
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"获取项目上下文失败: {projectId}");
                return null;
            }
        }

        /// <summary>
        /// 判断是否需要角色规划
        /// </summary>
        private bool DetermineCharacterPlanningNeed(ComplexIntent intent)
        {
            var keywords = new[] { "角色", "人物", "角色设定", "人物关系", "角色发展", "人物塑造" };
            return keywords.Any(k => intent.UserInput.Contains(k, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 判断是否需要工作流规划
        /// </summary>
        private bool DetermineWorkflowPlanningNeed(ComplexIntent intent)
        {
            var keywords = new[] { "流程", "步骤", "计划", "安排", "执行", "工作流", "任务" };
            return keywords.Any(k => intent.UserInput.Contains(k, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 确定规划范围
        /// </summary>
        private PlanningScope DeterminePlanningScope(ComplexIntent intent)
        {
            // 根据意图复杂度和类型确定规划范围
            if (intent.IntentType == IntentType.ProjectManagement)
                return PlanningScope.Project;
            else if (intent.IntentType == IntentType.ContentGeneration)
                return PlanningScope.Content;
            else
                return PlanningScope.Task;
        }

        /// <summary>
        /// 整合和优化规划
        /// </summary>
        private async Task<ComprehensivePlan> IntegrateAndOptimizePlanAsync(ComprehensivePlan plan)
        {
            // 使用AI服务优化规划的整合性和一致性
            var optimizationPrompt = BuildPlanOptimizationPrompt(plan);
            var optimizationResult = await _aiService.GenerateTextAsync(optimizationPrompt, 2000, 0.7f);
            
            // 解析优化建议并应用
            plan.OptimizationNotes = optimizationResult;
            plan.IsOptimized = true;
            
            return plan;
        }

        /// <summary>
        /// 构建规划优化提示
        /// </summary>
        private string BuildPlanOptimizationPrompt(ComprehensivePlan plan)
        {
            return $@"请分析以下综合规划方案，提供优化建议：

用户需求：{plan.UserIntent.OriginalRequest}

角色规划：{(plan.CharacterPlan != null ? "已包含" : "未包含")}
工作流规划：{(plan.WorkflowPlan != null ? "已包含" : "未包含")}

请提供：
1. 规划的完整性分析
2. 各部分之间的协调性建议
3. 执行顺序优化建议
4. 潜在风险和应对措施

优化建议：";
        }

        /// <summary>
        /// 生成优化建议
        /// </summary>
        private async Task<List<OptimizationSuggestion>> GenerateOptimizationSuggestionsAsync(
            PlanExecutionResult executionResult, 
            MonitoringResult monitoringResult)
        {
            var suggestions = new List<OptimizationSuggestion>();
            
            // 基于执行结果和监控数据生成优化建议
            if (monitoringResult.PerformanceMetrics.ExecutionTime > TimeSpan.FromMinutes(10))
            {
                suggestions.Add(new OptimizationSuggestion
                {
                    Type = OptimizationType.Performance,
                    Description = "执行时间较长，建议优化任务并行度",
                    Priority = OptimizationPriority.Medium,
                    AutoApplicable = true
                });
            }

            return suggestions;
        }

        /// <summary>
        /// 判断是否应该自动应用优化
        /// </summary>
        private bool ShouldAutoApplyOptimizations(List<OptimizationSuggestion> suggestions)
        {
            return suggestions.All(s => s.AutoApplicable && s.Priority != OptimizationPriority.High);
        }

        /// <summary>
        /// 应用优化建议
        /// </summary>
        private async Task<AutonomousPlanResult> ApplyOptimizationsAsync(AutonomousPlanResult result)
        {
            // 实现优化应用逻辑
            result.OptimizationsApplied = true;
            return result;
        }

        /// <summary>
        /// 保存规划文件到项目目录
        /// </summary>
        private async Task SavePlanningFilesAsync(AutonomousPlanResult result, string? projectId)
        {
            try
            {
                // 确定保存路径
                string savePath;
                if (!string.IsNullOrEmpty(projectId))
                {
                    // 如果有项目ID，尝试获取项目路径
                    savePath = await GetProjectPathAsync(projectId) ?? GetDefaultPlanningPath();
                }
                else
                {
                    savePath = GetDefaultPlanningPath();
                }

                var planningDir = Path.Combine(savePath, "自主规划");
                Directory.CreateDirectory(planningDir);

                var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");

                // 1. 保存规划概览
                var overviewPath = Path.Combine(planningDir, $"规划概览_{timestamp}.txt");
                var overviewContent = GeneratePlanningOverviewContent(result);
                await File.WriteAllTextAsync(overviewPath, overviewContent, System.Text.Encoding.UTF8);

                // 2. 保存角色规划（如果有）
                if (result.ExecutionResult.CharacterExecutionResult != null)
                {
                    var characterPath = Path.Combine(planningDir, $"角色规划_{timestamp}.txt");
                    var characterContent = GenerateCharacterPlanContent(result.ExecutionResult.CharacterExecutionResult);
                    await File.WriteAllTextAsync(characterPath, characterContent, System.Text.Encoding.UTF8);
                }

                // 3. 保存工作流规划（如果有）
                if (result.ExecutionResult.WorkflowExecutionResult != null)
                {
                    var workflowPath = Path.Combine(planningDir, $"工作流规划_{timestamp}.txt");
                    var workflowContent = GenerateWorkflowPlanContent(result.ExecutionResult.WorkflowExecutionResult);
                    await File.WriteAllTextAsync(workflowPath, workflowContent, System.Text.Encoding.UTF8);
                }

                // 4. 保存优化建议
                if (result.OptimizationSuggestions.Any())
                {
                    var optimizationPath = Path.Combine(planningDir, $"优化建议_{timestamp}.txt");
                    var optimizationContent = GenerateOptimizationContent(result.OptimizationSuggestions);
                    await File.WriteAllTextAsync(optimizationPath, optimizationContent, System.Text.Encoding.UTF8);
                }

                _logger.LogInformation($"规划文件已保存到: {planningDir}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存规划文件失败");
            }
        }

        /// <summary>
        /// 获取项目路径
        /// </summary>
        private async Task<string?> GetProjectPathAsync(string projectId)
        {
            try
            {
                // 尝试通过数据存储服务获取项目信息
                var projects = await _dataStorage.GetProjectsAsync();
                if (int.TryParse(projectId, out int id))
                {
                    var project = projects.FirstOrDefault(p => p.Id == id);
                    return project?.RootPath;
                }
                return null;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"获取项目路径失败，项目ID: {projectId}");
                return null;
            }
        }

        /// <summary>
        /// 获取默认规划保存路径
        /// </summary>
        private string GetDefaultPlanningPath()
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            return Path.Combine(documentsPath, "AI创作系统", "自主规划");
        }

        /// <summary>
        /// 生成规划概览内容
        /// </summary>
        private string GeneratePlanningOverviewContent(AutonomousPlanResult result)
        {
            var content = new System.Text.StringBuilder();
            content.AppendLine("# 自主规划概览报告");
            content.AppendLine($"生成时间: {result.CompletedAt:yyyy-MM-dd HH:mm:ss}");
            content.AppendLine($"执行状态: {(result.Success ? "成功" : "失败")}");
            content.AppendLine();

            if (result.ExecutionResult.StartedAt != default && result.ExecutionResult.CompletedAt.HasValue)
            {
                var duration = result.ExecutionResult.CompletedAt.Value - result.ExecutionResult.StartedAt;
                content.AppendLine($"执行时间: {duration:hh\\:mm\\:ss}");
            }

            content.AppendLine();
            content.AppendLine("## 执行摘要");
            content.AppendLine(result.Summary);

            if (result.MonitoringResult.PerformanceMetrics != null)
            {
                content.AppendLine();
                content.AppendLine("## 性能指标");
                content.AppendLine($"- 完成任务数: {result.MonitoringResult.PerformanceMetrics.TasksCompleted}");
                content.AppendLine($"- 失败任务数: {result.MonitoringResult.PerformanceMetrics.TasksFailed}");
                content.AppendLine($"- 成功率: {result.MonitoringResult.PerformanceMetrics.SuccessRate:P2}");
            }

            return content.ToString();
        }

        /// <summary>
        /// 生成角色规划内容
        /// </summary>
        private string GenerateCharacterPlanContent(CharacterExecutionResult characterResult)
        {
            var content = new System.Text.StringBuilder();
            content.AppendLine("# 角色规划报告");
            content.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            content.AppendLine();

            content.AppendLine("## 创建的角色");
            foreach (var character in characterResult.CreatedCharacters)
            {
                content.AppendLine($"- {character.Name}: {character.Description}");
            }

            content.AppendLine();
            content.AppendLine("## 更新的角色");
            foreach (var characterId in characterResult.UpdatedCharacters)
            {
                content.AppendLine($"- 角色ID: {characterId}");
            }

            return content.ToString();
        }

        /// <summary>
        /// 生成工作流规划内容
        /// </summary>
        private string GenerateWorkflowPlanContent(WorkflowExecutionResult workflowResult)
        {
            var content = new System.Text.StringBuilder();
            content.AppendLine("# 工作流规划报告");
            content.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            content.AppendLine();

            content.AppendLine("## 执行步骤");
            foreach (var stepResult in workflowResult.StepResults)
            {
                content.AppendLine($"- 步骤ID: {stepResult.StepId}");
                content.AppendLine($"  状态: {stepResult.Status}");
                if (stepResult.StartedAt != default && stepResult.CompletedAt.HasValue)
                {
                    var duration = stepResult.CompletedAt.Value - stepResult.StartedAt;
                    content.AppendLine($"  耗时: {duration:hh\\:mm\\:ss}");
                }
                content.AppendLine();
            }

            return content.ToString();
        }

        /// <summary>
        /// 生成优化建议内容
        /// </summary>
        private string GenerateOptimizationContent(List<OptimizationSuggestion> suggestions)
        {
            var content = new System.Text.StringBuilder();
            content.AppendLine("# 优化建议报告");
            content.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            content.AppendLine();

            foreach (var suggestion in suggestions.OrderBy(s => s.Priority))
            {
                content.AppendLine($"## {suggestion.Type} - {suggestion.Priority}");
                content.AppendLine(suggestion.Description);
                content.AppendLine($"可自动应用: {(suggestion.AutoApplicable ? "是" : "否")}");
                content.AppendLine();
            }

            return content.ToString();
        }
    }
}
